import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/user'
import type { UserInfo } from '@/api/user'
import { STATIC_BASE_URL, RESOURCE_BASE_URL } from '@/config'

// 添加处理资源 URL 的工具函数
const getFullResourceUrl = (url: string | null): string | null => {
  if (!url) return null;
  
  // 如果已经是完整的 URL，直接返回
  if (url.startsWith('http')) {
    return url;
  }
  
  // 如果是本地资源路径（以 /src 开头）
  if (url.startsWith('/src/')) {
    return url;
  }

  // 其他所有资源都直接拼接资源服务器地址
  return `${RESOURCE_BASE_URL}/${url.startsWith('/') ? url.slice(1) : url}`;
};

/**
 * 用户状态管理
 */
export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const userId = ref<number | null>(null)
  const username = ref<string | null>(null)
  const backgroundImage = ref<string | null>(null)
  const backgroundColor = ref<string | null>(null)
  const isLoggedIn = ref(!!token.value)

  /**
   * 保存token到本地存储，有效期一个月
   */
  const saveToken = (newToken: string) => {
    token.value = newToken
    isLoggedIn.value = true
    
    const expiryDate = new Date()
    expiryDate.setMonth(expiryDate.getMonth() + 1)
    
    localStorage.setItem('token', newToken)
    localStorage.setItem('tokenExpiry', expiryDate.toISOString())
  }

  /**
   * 清除用户状态和本地存储
   */
  const clearUserState = () => {
    token.value = null
    userId.value = null
    username.value = null
    backgroundImage.value = null
    backgroundColor.value = null
    isLoggedIn.value = false
    localStorage.removeItem('token')
    localStorage.removeItem('tokenExpiry')
    document.documentElement.style.setProperty('--theme-color', '#7EE1C8')
  }

  /**
   * 用户注册
   */
  const registerUser = async (userUsername: string, password: string) => {
    const result = await userApi.register(userUsername, password)
    if (result.success && result.token && result.user) {
      saveToken(result.token)
      userId.value = result.user.userId
      username.value = userUsername
      backgroundImage.value = result.user.backgroundImage || null
    }
    return result
  }

  /**
   * 用户登录
   */
  const loginUser = async (userUsername: string, password: string) => {
    const result = await userApi.login(userUsername, password)
    
    if (result.success && result.data) {
      saveToken(result.data.token)
      userId.value = result.data.user.userId
      username.value = userUsername
      backgroundImage.value = result.data.user.backgroundImage || null
    }
    return result
  }

  /**
   * 退出登录
   */
  const logout = () => {
    clearUserState()
  }

  /**
   * 检查并更新用户信息
   */
  const checkAndUpdateUserInfo = async () => {
    // 检查token是否存在且未过期
    const storedToken = localStorage.getItem('token')
    const tokenExpiry = localStorage.getItem('tokenExpiry')

    if (!storedToken || !tokenExpiry || new Date(tokenExpiry) < new Date()) {
      clearUserState()
      return false
    }

    // 获取用户信息
    const result = await userApi.getUserInfo()
    if (result.success && result.user) {
      userId.value = result.user.userId
      username.value = result.user.username
      backgroundImage.value = getFullResourceUrl(result.user.backgroundImage)
      if (result.user.backgroundColor) {
        backgroundColor.value = result.user.backgroundColor
        document.documentElement.style.setProperty('--theme-color', result.user.backgroundColor)
      }
      return true
    } else {
      clearUserState()
      return false
    }
  }

  /**
   * 上传背景图片
   */
  const uploadBackground = async (file: File) => {
    const result = await userApi.uploadBackground(file)
    if (result.success && result.backgroundUrl) {
      backgroundImage.value = getFullResourceUrl(result.backgroundUrl)
    }
    return result
  }

  /**
   * 获取当前token
   */
  const getToken = (): string | null => {
    return token.value
  }

  /**
   * 更新背景色（主题色）
   */
  const updateBackgroundColor = async (color: string) => {
    const result = await userApi.updateBackgroundColor(color)
    if (result.success) {
      backgroundColor.value = color
      document.documentElement.style.setProperty('--theme-color', color)
    }
    return result
  }

  // 初始化时检查token
  if (token.value) {
    checkAndUpdateUserInfo()
  }

  return {
    // 状态
    token,
    userId,
    username,
    backgroundImage,
    backgroundColor,
    isLoggedIn,
    
    // 方法
    registerUser,
    loginUser,
    logout,
    checkAndUpdateUserInfo,
    uploadBackground,
    getToken,
    updateBackgroundColor,
  }
})
// 导出一个获取token的辅助函数
export const getToken = () => {
  const store = useUserStore()
  return store.getToken()
}

